<template>
    <div class="container" ref="containerRef"></div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
// 导入Three.js库
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
// 定义一个引用，用于后续引用包含渲染器的DOM元素
const containerRef = ref<HTMLDivElement>();
// 初始化渲染器，并设置其大小与当前窗口大小一致
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// 创建一个透视相机，并设置其位置和视角
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 5000);
camera.position.set(15, 10, 15);
camera.lookAt(0, 0, 0);

// 创建一个场景对象
const scene = new THREE.Scene();

const ambientLight = new THREE.AmbientLight(0xffffff, 1); // 白光，强度为1
scene.add(ambientLight);
const dirLight = new THREE.DirectionalLight('rgb(255,255,255)', 5);
dirLight.position.set(10, 10, 5);
scene.add(dirLight);

const loader = new GLTFLoader();
const axesHelper = new THREE.AxesHelper(1000);
scene.add(axesHelper);

const url = new URL('./glTF-Binary/bai/bai.gltf', import.meta.url);
let mixer: THREE.AnimationMixer;
loader.load(url.href, gltf => {
    // ✅ 关键步骤：设置动画混合器
    mixer = new THREE.AnimationMixer(gltf.scene);
    // 获取所有动画剪辑
    const clips = gltf.animations;
    // 播放所有动画（或按需选择特定动画）
    clips.forEach((clip) => {
        const action = mixer.clipAction(clip);
        action.play();
    });

    scene.add(gltf.scene);
});

window.onresize = function () {
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.render(scene, camera);
};

const controls = new OrbitControls(camera, renderer.domElement);
controls.addEventListener('change', function () {
    renderer.render(scene, camera);
});

const clock = new THREE.Clock();
const animate = () => {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
    controls.update();
    // ✅ 更新动画混合器
    if (mixer) {
        mixer.update(clock.getDelta());
    }
}

animate();
onMounted(() => {
    containerRef.value?.appendChild(renderer.domElement);
});

</script>
<style lang="scss" scoped></style>
